<?php


namespace app\common\service\worker;


use app\admin\model\SystemErrorLog;
use think\worker\Server;

class WorkerService extends Server
{
    protected bool $daemonize = true;//断线重连
    protected int $max_connect = 100000;

    public function __construct()
    {
        $this->socket = config('worker_server.socket') ?? $this->socket;
        $this->protocol = config('worker_server.protocol') ?? $this->protocol;
        $this->host = config('worker_server.host') ?? $this->host;
        $this->port = config('worker_server.port') ?? $this->port;
        $this->option = [
            'name' => 'Tp6Worker',//自定义名字
//            'logFile'   => '/tmp/workerman.log',//业务输出日志
//            'stdoutFile'    => ''//workerman系统日志
        ];
        parent::__construct();
    }

    public function onWorkerStart()
    {
//        SystemErrorLog::init()->addError('worker start');
    }

    public function onWorkerReload()
    {
//        SystemErrorLog::init()->addError('worker reload');
    }

    public function onConnect($connection)
    {
        SystemErrorLog::init()->addError('worker connect');
        $connection->send('连接成功');
        $connection->onMessage = function ($connection, $data) {
            static $request_count = 0;// 已经处理请求数
            if (++$request_count > $this->max_connect) {//最大连接数
                $this->worker->stopAll();
            }
            //业务逻辑在这里
            $connection->send('我：' . json_encode($data));//测试期间原样返回
        };
    }

    public function onClose($connection)
    {
//        SystemErrorLog::init()->addError('worker close');
        echo '连接中断';
    }

//    public function onMessage($connection,$data){
//        不要在这里面写，会继承给所有连接，导致逻辑混乱和资源浪费，写在onConnect后
//        $connection->send('我说：'.json_encode($data));
//    }


    public function onError($connection, $code, $msg)
    {
        echo "error [ $code ] $msg\n";
    }

    function onBufferFull($connection)
    {
        echo "bufferFull and do not send again\n";
    }

    function onBufferDrain($connection)
    {
        echo "buffer drain and continue send\n";
    }


}